﻿#include "SplitSettingWidget.h"
#include <QMessageBox>
#include "DataTrans.h"
#include <QInputDialog>
#include <QApplication.h>

QString SplitResult::RecordInfo::LevelText()
{
	QString name = (Level < 15) ? QString('A' + Level) : qApp->translate("main","落选");
	return name;
}

QString SplitResult::RecordInfo::TimeText()
{
	return DataTrans::fromTimeUnit(Time);
}

//
SplitSettingWidget::SplitSettingWidget(QWidget *parent)
	: QWidget(parent)
{
	ui.setupUi(this);

	//tableSplit
	QStringList strListSelect;
	strListSelect << tr("序号") << tr("名称");
	UiHelper::SetTable(ui.tableSplitSelect, strListSelect);

	//
	QStringList strListSplit;
	strListSplit << tr("等级") << tr("放电容量") << tr("放电中值电压");	
	ui.tableWidgetSplit->setColumnCount(strListSplit.size());
	ui.tableWidgetSplit->setHorizontalHeaderLabels(strListSplit);

	ui.tableWidgetSplit->setSelectionMode(QAbstractItemView::SingleSelection); //单击选择一行  
	ui.tableWidgetSplit->setSelectionBehavior(QAbstractItemView::SelectRows);  //设置只能选择一行，不能多行选			
	ui.tableWidgetSplit->verticalHeader()->hide();
	
	ui.tableWidgetSplit->setRowCount(15);
	for (int i = 0; i < 15; i++)
	{
		QTableWidgetItem *item = new QTableWidgetItem(QString('A' + i));
		QTableWidgetItem *item1 = new QTableWidgetItem();
		QTableWidgetItem *item2 = new QTableWidgetItem();
		item->setFlags(item->flags() & (~Qt::ItemIsEditable));
		ui.tableWidgetSplit->setItem(i, 0, item);
		ui.tableWidgetSplit->setItem(i, 1, item1);
		ui.tableWidgetSplit->setItem(i, 2, item2);
	}

	ui.boxSplitType->addItem(tr("放电容量"));
	ui.boxSplitType->addItem(tr("放电中值电压"));
	ui.boxSplitType->addItem(tr("放电容量及中值电压"));
}

SplitSettingWidget::~SplitSettingWidget()
{
}

void SplitSettingWidget::init()
{
	updateSplitTable();	
}

std::array<SplitInfo::Range, MAX_SPLIT_LEVEL> SplitSettingWidget::range()
{
	int idx = ui.boxSplitType->currentIndex();
	return m_range[idx];
}

void SplitSettingWidget::on_btnSplitEqual_clicked()
{
	double min = ui.spinSplitMin->value();
	double max = ui.spinSplitMax->value();
	int count = ui.spinSplitNum->value();	
	if (min >= max)
	{
		QMessageBox::information(this, "", tr("分选条件设置错误"));
		return;
	}

	int split_type = ui.boxSplitType->currentIndex();
	QVector<int> types;
	if (split_type == 2)
		types << 0 << 1;
	else
		types << split_type;

	for (int type_idx = 0; type_idx < types.size(); type_idx++)
	{
		int idx = types[type_idx] + 1;
		for (int i = 0; i < 15; i++)
			ui.tableWidgetSplit->item(i, idx)->setText("");

		double gap = (max - min) / count;
		double e = max;
		double s = max - gap;
		for (int i = 0; i < count; i++)
		{
			if (i == count - 1)
				s = min;

			QString text = QString::asprintf("%0.2f , %0.2f", s, e);
			ui.tableWidgetSplit->item(i, idx)->setText(text);

			s -= gap;
			e -= gap;
		}
	}
}

void SplitSettingWidget::on_btnSplit_clicked()
{
	if (!uiToRange())
		return;

	emit sigPrepareData();

	result.error = false;
	result.erroNum = -1;
	result.indexs.clear();
	result.indexs.resize(16);
	result.recordList.clear();
	result.sumItem = recordList.size();	

	for (int i = 0; i < recordList.size(); i++)
	{
		SplitResult::RecordInfo info;
		int level = splitRecord(recordList[i],info);
		if (level == -1)
		{
			result.erroNum = i;
			result.error = true;
			break;
		}
		result.indexs[level].push_back(i);
		result.recordList.push_back(info);
	}

	emit sigSplitFinish();
}

void SplitSettingWidget::on_btnSaveSplit_clicked()
{	
	if (!uiToRange())
		return;

	QString name = QInputDialog::getText(this, "", tr("请输入名称"));
	if (name.isEmpty())
		return;

	SplitInfo info;
	info.name = name;
	info.rangeList[0] = m_range[0];
	info.rangeList[1] = m_range[1];

	auto list = g_project->splitInfoList();
	list.push_back(info);
	g_project->setSplitInfoList(list);
	
	updateSplitTable();
}

void SplitSettingWidget::on_btnDeleteSplit_clicked()
{
	int idx = ui.tableSplitSelect->currentRow();
	if (idx < 0)
		return;

	auto list = g_project->splitInfoList();
	list.remove(idx);
	g_project->setSplitInfoList(list);

	updateSplitTable();
}

void SplitSettingWidget::on_tableSplitSelect_itemDoubleClicked(QTableWidgetItem *item)
{
	int idx = ui.tableSplitSelect->currentRow();
	if (idx < 0)
		return;

	auto list = g_project->splitInfoList();
	rangeToUi(list[idx].rangeList);	
}

bool SplitSettingWidget::parseRange(QString text, SplitInfo::Range &range)
{	
	text.trimmed();
	if (text.isEmpty())
	{
		range.vaild = false;
		return true;
	}

	QStringList list = text.split(",");
	if (list.size() != 2)
		return false;

	bool ok1, ok2;
	double low = list[0].toDouble(&ok1);
	double upper = list[1].toDouble(&ok2);
	if (!ok1 || !ok2)
		return false;

	range.vaild = true;
	range.lower = low;
	range.upper = upper;
	return true;
}

void SplitSettingWidget::rangeToUi(std::array<SplitInfo::Range, MAX_SPLIT_LEVEL> *ranges)
{	
	int count = ui.tableWidgetSplit->rowCount();
	for (int idx = 0; idx < 2; idx++)
	{
		for (int i = 0; i < count; i++)
		{
			if (ranges[idx][i].vaild)
			{
				QString text = QString::asprintf("%0.2f,%0.2f", ranges[idx][i].lower, ranges[idx][i].upper);
				ui.tableWidgetSplit->item(i, idx + 1)->setText(text);
			}
			else
				ui.tableWidgetSplit->item(i, idx + 1)->setText("");
		}
	}
}

bool SplitSettingWidget::rangeVaild(int index, int type)
{
	if (type != 2)
	{
		if (m_range[type][index].vaild)
			return true;
	}
	else
	{
		if (m_range[0][index].vaild && m_range[1][index].vaild)
			return true;
	}

	return false;
}

bool SplitSettingWidget::uiToRange()
{
	int type = ui.boxSplitType->currentIndex();
	int count = ui.tableWidgetSplit->rowCount();	

	for (int idx = 0; idx < 2; idx++)
	{
		for (int i = 0; i < count; i++)
		{
			if (!parseRange(ui.tableWidgetSplit->item(i, idx + 1)->text(), m_range[idx][i]))
			{
				QString tips = tr("第行%1,第列%2 数据范围错误,请检查").arg( QString::number(i + 1), QString::number(idx + 2));
				QMessageBox::information(this, "", tips);
				return false;
			}
		}		
	}

	int vaild_num = 0;
	for (int i = 0; i < (int)m_range[type].size(); i++)
	{		
		if (rangeVaild(i,type))
			vaild_num++;		
	}

	if (vaild_num == 0)
	{
		QMessageBox::information(this, "", tr("至少要有一组分选数据"));
		return false;
	}

	return true;
}

void SplitSettingWidget::updateSplitTable()
{
	QVector<SplitInfo> list = g_project->splitInfoList();
	ui.tableSplitSelect->clearContents();
	ui.tableSplitSelect->setRowCount(list.size());
	for (int i = 0; i < list.size(); i++)
	{
		QTableWidgetItem *itemNo = new QTableWidgetItem(QString::number(i + 1));
		QTableWidgetItem *itemName = new QTableWidgetItem(list[i].name);

		ui.tableSplitSelect->setItem(i, 0, itemNo);
		ui.tableSplitSelect->setItem(i, 1, itemName);
	}
}

int SplitSettingWidget::splitRecord(BTERecordPtr record,SplitResult::RecordInfo &info)
{	
	int type = ui.boxSplitType->currentIndex();				
	int split_ret = 15; //落选
	if (record->info.dataCache.beginDis >= 0)
	{	
		info.DisChargeCap = record->info.dataCache.endDisCap;
		info.DisChargeEng = record->info.dataCache.endDisEng;
		info.Time = record->info.dataCache.endDisTestTime;
		info.MeanVoltage = record->info.dataCache.midDisVoltage;
				
		//查找计算结果		
		for (int i = 0; i < (int)m_range[0].size(); i++)
		{
			if (!rangeVaild(i, type))
				continue;
			
			if ((type == 0 && info.DisChargeCap >= m_range[0][i].lower && info.DisChargeCap <= m_range[0][i].upper)
				|| (type == 1 && info.MeanVoltage >= m_range[1][i].lower && info.MeanVoltage <= m_range[1][i].upper)
				|| (type == 2 && info.DisChargeCap >= m_range[0][i].lower && info.DisChargeCap <= m_range[0][i].upper
					&& info.MeanVoltage >= m_range[1][i].lower && info.MeanVoltage <= m_range[1][i].upper))
			{
				split_ret = i;
				break;
			}			
		}
	}
	else
	{
		info.DisChargeCap = 0;
		info.DisChargeEng = 0;
		info.Time = 0;
		info.MeanVoltage = 0;
	}
	info.CellNo = record->info.stepInfo.cellNo;
	info.CellPatch = record->info.stepInfo.cellBatch;
	info.Level = split_ret;
	info.itemIndex = record->info.itemIndex;

	return split_ret;
}